import axios from 'axios'
//import Cookies from 'js-cookie'
import {
	API_BASE_URL,
	TOKEN_KEY
} from '@/api/config'

import store from '@/store/index'
// axios 配置
axios.defaults.timeout = 5000
axios.defaults.baseURL = API_BASE_URL
// http request 拦截器
axios.interceptors.request.use(
	config => {
		if (store.state.token) {
			config.headers.Authorization = store.state.token
			config.headers[TOKEN_KEY] = store.state.token
		}
		config.headers['Content-Type']='application/x-www-form-urlencoded'
		return config
	},
	err => {
		return Promise.reject(err)
	},
)

// http response 拦截器
axios.interceptors.response.use(
	response => {
		return response
	},
	error => {
		if (error.response) {
			switch (error.response.status) {
				case 401:
					// 401 清除token信息并跳转到登录页面
					store.commit('removeToken')

					// 只有在当前路由不是登录页面才跳转
					router.currentRoute.path !== 'login' &&
						router.replace({
							path: 'login',
							query: {
								redirect: router.currentRoute.path
							},
						})
			}
		}
		// console.log(JSON.stringify(error));//console : Error: Request failed with status code 402
		return Promise.reject(error.response)
	},
)

export default axios
